#!/usr/bin/env python

"""
import Karalhoky as main module

def Authors():
	tharis20 (main)
	triton (mini-org) <triton@portugal-a-programar.org>

def License():
	GPL v2
"""

import sys,string,time,os
from thread import start_new_thread as nthread

from LRCParser import *
from Player import *
from CairoOutput import *

import gtk
import gobject

class Karaoke:
	def __init__(self):

		self.fetch()
		
		self.Player=Finder().find()
		
		self.Win=LyricWindow('Karalhoky')
		self.Win.present()
		
		nthread(self.start,())

	"Fetch the Database"
	def fetch(self):
		db = open("source.kdb",'r').readlines()

		self.db = {}

		# even = MP's name | Odd = File
		for i in range(0, len(db), 2):
			self.db[db[i][0:-1]] = db[i+1][0:-1]


	"Play Lyrics Function"
	def play(self):
		
		elapsed = self.Player.Elapsed()
		print elapsed
		
		# check for the nearest greater time
		for i in range(len(self.times)):
			if self.times[i] > elapsed+1:
				break

		# wait until reaching next lyric time
		time.sleep(self.times[i]-self.Player.Elapsed())

		# put lyric and sleep until next lyric
		for j in range(i, len(self.times)):

			self.Win.lyric.set_text(self.lyrics[self.times[j]])
			
			if j+1<len(self.times):
				time.sleep(self.times[j+1]-self.times[j])
				
			if self.new:
				self.Win.lyric.set_text("Karalhoky")
				return

		self.Win.lyric.set_text("Karalhoky")

	"The Main Start Function"
	def start(self):    
		if not self.Player: # no supported player found
			print "No supported player running"
			exit() # end the program

		self.paused = False
		
		self.loop()
	
	def loop(self):
		cur = None
		while True:
			song = self.Player.Current()
			
			if cur != song:
				cur = song
				self.new = True
			
			status = self.Player.Status()
			 
			# player running and got a new song
			if status == "playing" and self.new:
				self.new = False
				print(cur, status)
								
				# check the db for lyrics
				if self.db.has_key(cur):
					res = LRCParser(self.db[cur]).parse()
					self.times = res[0]
					self.lyrics = res[1]
					self.play()
				# lyric not found in db, fetch from web
				else:
					self.Win.lyric.set_text("No Karaoke File for This Song")
					
			time.sleep(1)
			
if __name__ == "__main__":
	k=Karaoke()
	gobject.threads_init()
	try:
		gtk.main()
	except KeyboardInterrupt:
		pass
